<template>
  <el-dialog :title="id ? '修改景点' : '新增景点'" :visible.sync="dialogFormVisible" width="600px">
    <el-form
      ref="dataForm"
      :rules="rules"
      :model="temp"
      label-position="left"
      label-width="140px"
      style="margin: 0 30px"
    >
      <template>
        <el-form-item label="景点名称" prop="name">
          <el-input v-model="temp.name" placeholder="请输入景点名称" />
        </el-form-item>

        <el-form-item label="收费模式" prop="charging_mode">
          <el-select
            v-model="temp.charging_mode"
            filterable
            placeholder="请选择"
            style="width: 100%"
            @change="changeChargingMode"
          >
            <el-option
              v-for="item in chargingModeOptions"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <template v-if="temp.charging_mode === 'time'">
          <el-form-item label="收费时段" required>
            <ul class="time-slot">
              <li>
                <p>超过</p>
                <el-input
                  v-model="temp.time_price_rule.time_slot1.minutes"
                  type="number"
                  style="width: 100px"
                  disabled
                />
                <p>分钟，收费</p>
                <el-input
                  v-model="temp.time_price_rule.time_slot1.price"
                  type="number"
                  style="width: 100px"
                />
                <p>元</p>
              </li>
              <li>
                <p>超过</p>
                <el-input
                  v-model="temp.time_price_rule.time_slot2.minutes"
                  type="number"
                  style="width: 100px"
                />
                <p>分钟，收费</p>
                <el-input
                  v-model="temp.time_price_rule.time_slot2.price"
                  type="number"
                  style="width: 100px"
                />
                <p>元</p>
              </li>
              <li>
                <p>超过</p>
                <el-input
                  v-model="temp.time_price_rule.time_slot3.minutes"
                  type="number"
                  style="width: 100px"
                />
                <p>分钟，收费</p>
                <el-input
                  v-model="temp.time_price_rule.time_slot3.price"
                  type="number"
                  style="width: 100px"
                />
                <p>元</p>
              </li>
            </ul>
          </el-form-item>
        </template>
        <template v-if="temp.charging_mode === 'daily'">
          <el-form-item label="按日计费">
            <el-input v-model="temp.daily_price_rule.day_price" placeholder="请输入租金费用" />
          </el-form-item>
        </template>
        <template v-if="temp.charging_mode === 'flat'">
          <el-form-item label="一口价计费">
            <el-input v-model="temp.flat_price_rule.flat_price" placeholder="请输入租金费用" />
          </el-form-item>
        </template>
        <el-form-item label="押金费用" prop="deposit">
          <el-input v-model="temp.deposit" placeholder="请输入押金费用" />
        </el-form-item>
        <el-form-item label="免费时间(分钟)" prop="free_time">
          <el-input v-model="temp.free_time" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="最大可租借数量" prop="max_rent_num">
          <el-select v-model="temp.max_rent_num" placeholder="请选择" style="width: 100%">
            <el-option v-for="item in maxRentNumOptions" :key="item" :label="item" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="景点地址" prop="city">
          <el-cascader
            v-model="temp.city"
            :options="city_options"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="">
          <el-input v-model="temp.address" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="分区数" prop="part_num">
          <el-select
            v-model="temp.part_num"
            filterable
            placeholder="请选择"
            style="width: 100%"
            @change="handleZoneCountChange"
          >
            <el-option v-for="item in zoneCountOptions" :key="item" :label="item" :value="item">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 动态显示区域比例输入框 -->
        <template v-if="temp.part_num > 0">
          <el-form-item
            v-for="(item, index) in temp.part_props"
            :key="index"
            :label="`区域${index + 1}`"
            :prop="`part_props[${index}].ratio`"
            :rules="zoneRatioRules"
          >
            <el-input
              v-model="temp.part_props[index].ratio"
              type="number"
              placeholder="请输入分配比例"
              @change="validateZoneRatios(index)"
            >
              <template slot="append">%</template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <div class="zone-ratio-sum">当前比例总和: {{ zoneRatioSum }}%</div>
            <div v-if="zoneRatioSum > 100" class="zone-ratio-error">比例总和不能超过100%</div>
          </el-form-item>
        </template>
      </template>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取消</el-button>
      <el-button type="primary" @click="saveData">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getDetail, add, edit } from '@/api/attraction'
import { getCityList } from '@/api/common'
const rule = [{ required: true, message: '必填项不能为空' }]
export default {
  name: 'AttractionEdit',

  data() {
    return {
      dialogFormVisible: false,
      id: '',
      maxRentNumOptions: [3, 4, 5, 6],
      temp: {
        name: '',
        max_rent_num: 3,
        charging_mode: '',
        time_price_rule: {
          time_slot1: {
            minutes: '0',
            price: 0
          },
          time_slot2: {
            minutes: '',
            price: ''
          },
          time_slot3: {
            minutes: '',
            price: ''
          }
        },
        daily_price_rule: { day_price: '' },
        flat_price_rule: { flat_price: '' },
        deposit: '',
        free_time: '',
        city: [],
        address: '',
        part_num: '',
        part_props: [] // 将保持为对象数组格式 [{id: 1, ratio: "30"}]
      },
      rules: {
        name: rule,
        deposit: rule,
        free_time: rule,
        charging_mode: [{ required: true, message: '请选择收费模式', trigger: 'change' }],
        city: [{ required: true, message: '请选择城市', trigger: 'change' }]
      },
      zoneRatioRules: [
        { required: true, message: '请输入分配比例', trigger: 'blur' },
        {
          type: 'number',
          message: '比例必须为数字',
          trigger: 'blur',
          transform: (value) => Number(value)
        },
        {
          validator: (rule, value, callback) => {
            if (value < 0 || value > 100) {
              callback(new Error('比例必须在0-100之间'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ],
      chargingModeOptions: [
        { name: '分时段计费', value: 'time' },
        { name: '按日计费', value: 'daily' },
        { name: '一口价模式', value: 'flat' }
      ],
      zoneCountOptions: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
      city_options: []
    }
  },
  computed: {
    zoneRatioSum() {
      if (!this.temp.part_props || this.temp.part_props.length === 0) return 0
      return this.temp.part_props.reduce((sum, item) => {
        const value = parseFloat(item.ratio) || 0
        return sum + value
      }, 0)
    }
  },
  created() {
    getCityList().then((res) => {
      this.city_options = this.transformData(res.data)
    })
  },
  methods: {
    transformData(data) {
      return data.map((item) => {
        const transformedItem = {
          value: item.code, // 替换 code 为 value
          label: item.name // 替换 name 为 label
        }

        // 如果存在 cities，则递归转换为 children
        if (item.cities && item.cities.length > 0) {
          transformedItem.children = this.transformData(item.cities)
        }
        return transformedItem
      })
    },
    handleChange(value) {
      console.log('value', value)
      this.temp.city = value
    },

    // 删除这个重复的函数
    // 处理分区数变化
    // handleZoneCountChange(value) {
    //   // 创建对应数量的区域
    //   this.temp.part_props = []
    //   for (let i = 0; i < value; i++) {
    //     this.temp.part_props.push({
    //       id: i + 1,
    //       ratio: ''
    //     })
    //   }
    // },

    // 验证区域比例总和
    validateZoneRatios(index) {
      console.log('validateZoneRatios', index)
    },

    handleCreate() {
      this.id = ''
      this.temp = {
        name: '',
        max_rent_num: 3,
        charging_mode: '',
        time_price_rule: {
          time_slot1: {
            minutes: '0',
            price: 0
          },
          time_slot2: {
            minutes: '',
            price: ''
          },
          time_slot3: {
            minutes: '',
            price: ''
          }
        },
        daily_price_rule: { day_price: '' },
        flat_price_rule: { flat_price: '' },
        deposit: '',
        free_time: '',
        city: [],
        address: '',
        part_num: '',
        part_props: []
      }
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs.dataForm.clearValidate()
      })
    },
    // 编辑
    handleEdit(id) {
      getDetail(id).then((res) => {
        this.id = id
        Object.assign(this.temp, res.data)

        // 确保part_props存在且格式正确
        if (!this.temp.part_props) {
          this.temp.part_props = []
        } else if (Array.isArray(this.temp.part_props)) {
          // 确保每个元素都是对象格式 {id: number, ratio: string}
          if (this.temp.part_props.length > 0 && typeof this.temp.part_props[0] !== 'object') {
            // 如果是纯数值数组，转换为对象数组
            this.temp.part_props = this.temp.part_props.map((ratio, index) => ({
              id: index + 1,
              ratio: ratio
            }))
          }
        }

        // 如果part_num存在但part_props为空或长度不匹配，初始化part_props
        if (
          this.temp.part_num > 0 &&
          (this.temp.part_props.length === 0 || this.temp.part_props.length !== this.temp.part_num)
        ) {
          this.handleZoneCountChange(this.temp.part_num)
        }

        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      })
    },

    // 处理分区数变化
    handleZoneCountChange(value) {
      // 保存现有的区域数据
      const existingProps = this.temp.part_props || []

      // 创建对应数量的区域
      this.temp.part_props = []
      for (let i = 0; i < value; i++) {
        // 如果存在现有数据，保留它
        if (existingProps[i]) {
          this.temp.part_props.push(existingProps[i])
        } else {
          this.temp.part_props.push({
            id: i + 1,
            ratio: ''
          })
        }
      }
    },

    /**
     * @description: 切换计费规则
     */
    changeChargingMode(val) {
      if (val === 'time') {
        this.temp.time_price_rule = {
          time_slot1: {
            minutes: '0',
            price: 0
          },
          time_slot2: {
            minutes: '',
            price: ''
          },
          time_slot3: {
            minutes: '',
            price: ''
          }
        }
      } else if (val === 'daily') {
        this.temp.daily_price_rule = { day_price: '' }
      } else {
        this.temp.flat_price_rule = { flat_price: '' }
      }
    },
    // 保存
    saveData() {
      if (this.zoneRatioSum > 100) {
        return this.$message.warning('所有区域的比例之和不能超过100%')
      }
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          if (this.temp.charging_mode === 'time') {
            delete this.temp.daily_price_rule
            delete this.temp.flat_price_rule
          } else if (this.temp.charging_mode === 'daily') {
            delete this.temp.time_price_rule
            delete this.temp.flat_price_rule
          } else {
            delete this.temp.time_price_rule
            delete this.temp.daily_price_rule
          }

          // 深拷贝数据
          const d = JSON.parse(JSON.stringify(this.temp))

          // 不需要再转换part_props，因为已经是正确的格式

          console.log('this.temp', d)
          const p = this.id ? edit(this.id, d) : add(d)
          p.then(() => {
            this.$parent.fetchData()
            this.dialogFormVisible = false
            this.$parent.$notify({
              title: '成功',
              message: this.id ? '修改成功' : '添加成功',
              type: 'success'
            })
          })
        }
      })
    }
  }
}
</script>
<style scoped lang="less">
.item-p {
  margin: 0;
  /* height: 1px; */
}
.time-slot {
  list-style: none;
  padding: 0;
  margin: 0;
  li {
    padding: 0;
    margin: 10px 0;
    display: flex;
    align-items: center;
    p {
      padding: 0 5px;
    }
  }
}
.zone-ratio-sum {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}
.zone-ratio-error {
  color: #f56c6c;
  font-size: 14px;
  font-weight: bold;
}
</style>
